package com.hyny.framework.platform.system.utils;

import net.sf.jsqlparser.expression.Alias;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.PlainSelect;

import java.util.List;
import java.util.stream.Collectors;

/**
 *J SqlParser工具类,用于通过API的方式操作SQL语句
 */
public class ExpressionUtils {


    /**
     * 构建in sql
     * @param tableName
     * @param fieldName
     * @param values
     * @return
     */
    public static InExpression buildInSql(String tableName,String fieldName,List<String> values) {
        // 创建IN表达式对象，传入列名及IN范围列表
        return new InExpression(new Column(tableName + "." + fieldName), new ExpressionList(values.stream().map(StringValue::new).collect(Collectors.toList())));
    }

    /**
     * 构建eq sql
     * @param columnName 字段名称
     * @param value 字段值
     * @return EqualsTo
     */
    public static EqualsTo buildEq(String columnName, String value) {
        return new EqualsTo(new Column(columnName), new StringValue(value));
    }



    /**
     * 获取表名/别名
     * @param plainSelect plainSelect
     * @return 表名/别名
     */
    public static String getTableName(PlainSelect plainSelect) {
        Table table= (Table) plainSelect.getFromItem();
        return  table.getName() ;
    }


    /**
     * 获取表名/别名
     * @param plainSelect plainSelect
     * @return 表名/别名
     */
    public static String getAliasName(PlainSelect plainSelect) {
        // 获取别名
        Table table= (Table) plainSelect.getFromItem();
        Alias alias = table.getAlias();
        return alias==null?null:alias.getName();
    }




    /**
     * 将2个where条件拼接到一起
     * @param plainSelect plainSelect
     * @param appendExpression 待拼接条件
     */
    public static void appendExpression(PlainSelect plainSelect, Expression appendExpression) {
        Expression where = plainSelect.getWhere() == null ? appendExpression : new AndExpression(plainSelect.getWhere(), appendExpression);
        plainSelect.setWhere(where);
    }
}

